package com.ygqh.baby.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ygqh.baby.ao.CodeType;
import com.ygqh.baby.mapper.YgFrameCodeMapper;
import com.ygqh.baby.service.YgFrameCodeService;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.YgStringUtils;

@Service
public class YgFrameCodeServiceImpl implements YgFrameCodeService {

	@Autowired
	private YgFrameCodeMapper ygFrameCodeMapper;

	@Override
	public Long getFrameCode(CodeType codeType, Date date) {
		String formatDate = DateConvertUtils.format(date, "yyMMdd");
		long parseLong = Long.parseLong(formatDate);
		String randomNum = YgStringUtils.getRandomLong(codeType.getCode());
		Long num = Long.parseLong(randomNum);
		if (CodeType.SQCode.equals(codeType)) {
			if (num.compareTo(900l) > 0) {
				num = num - 100l;
			}
		}
		Long frameCode = ygFrameCodeMapper.getFrameCode(codeType, parseLong, num);

		String codeStr = formatDate + "" + frameCode;
		if (codeType.equals(CodeType.RechargeMB)) {
			codeStr = 6 + codeStr;
		}
		Long code = Long.parseLong(codeStr);
		return code;
	}

	@Override
	public String getFrameCode(CodeType codeType, Date date, int length) {
		String code = "";
		String formatDate = DateConvertUtils.format(date, "yyMMdd");
		long parseLong = Long.parseLong(formatDate);

		Long frameCode = 0L;
		synchronized (codeType) {
			frameCode = ygFrameCodeMapper.getFrameCode(codeType, parseLong, Long.parseLong("1"));
		}

		if (frameCode < 10) {
			for (int i = 0; i < length - 1; i++) {
				code += "0";
			}
		}
		code += frameCode;
		return formatDate + code;
	}

	@Override
	public String getFrameCode(CodeType codeType, Date date, String format, int length) {
		String code = "";
		String formatDate = DateConvertUtils.format(date, format);
		Long parseLong = Long.parseLong(formatDate);

		Long frameCode = ygFrameCodeMapper.getFrameCode(codeType, parseLong, Long.parseLong("1"));
		int size = frameCode.toString().length();

		for (int i = 0; i < length - size; i++) {
			code += "0";
		}
		code += frameCode;
		return formatDate + code;
	}

}
